/**
 * @param {number[]} nums
 * @param {number} target
 * @return {number}
 */
var threeSumClosest = function (nums, target) {
    nums.sort((a, b) => a - b)
    let n = nums.length
    let diff = Infinity
    let left = 1
    let right = n - 1
    for (let i = 0; i < n - 2; i++) {
        let cur = nums[i]
        left = i + 1
        right = n - 1
        while (left < right) {
            let sum = cur + nums[left] + nums[right]
            let curAbs = sum - target
            diff = Math.abs(curAbs) > Math.abs(diff) ? diff : curAbs
            if (sum === target) {
                return target
            } else if (sum > target) {
                right--
            } else {
                left++
            }
        }
    }
    return target + diff
};

let nums = [-1, 2, 1, -4], target = 1
console.log(threeSumClosest(nums, target));